package com.scujj.util;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

public class FileUtil {
    public static String uploadFile(String path, MultipartFile img) {
        String oldName = img.getOriginalFilename();
        String str = oldName.substring(oldName.lastIndexOf("."));
        if (!(str.contains("jpg") || str.contains("jpeg") || str.contains("png") || str.contains("gif") || str.contains("mp4") || str.contains("mp3"))) {
            return null;
        }
        String fileName = UUID.randomUUID() + str;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = img.getInputStream();
            outputStream = new FileOutputStream(path + fileName);
            FileCopyUtils.copy(inputStream, outputStream);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileName;
    }

    public static String uploadFiles(String rootPath,String dyPath, MultipartFile[] files){
        String imgPath=null;
        if(files!=null){
            StringBuilder sb=new StringBuilder();
            for(MultipartFile img:files){
                if(!img.isEmpty()){
                    sb.append("api-static/");
                    sb.append(dyPath);
                    sb.append(FileUtil.uploadFile(rootPath+dyPath,img));
                    sb.append(";");
                }
            }
            imgPath=sb.toString();
        }
        return imgPath;
    }
}
